
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';

const props:any = defineProps({
  file: {
    required: true
  }
})
const isIfarme = ref(false);
const isTxt = ref(false)
const isLoading = ref(true)
const txtContainer = ref()
function readerFile(file) {
  if(window.FileReader) {
				const reader = new FileReader();
				reader.onloadstart= (e) => {
					console.log("开始读取", e);
				};
				reader.onprogress= (e) => {
					console.log("正在读取",e);
				};
				reader.onerror= (e) => {
					console.log("读取出错",e);
          checkError()
				};
				reader.onabort= (e) => {
					console.log("读取中断",e);
          checkError()
				};
				reader.onload= (e) => {
					console.log("读取成功",e);
          txtContainer.value = e.target.result
          isIfarme.value = false
          isLoading.value = false
          isTxt.value = true
				};
				// 读取完成，无论成功失败：
				reader.onloadend = (e) => {
					console.log("读取文件操作 finally",e);
				};
        reader.readAsText(file,"utf-8");
			} else {
        console.log("Not supported by your browser!");
        checkError()
			};
}
function checkError() {
  // 保底处理
  isIfarme.value = true;
  isLoading.value = false;
  isTxt.value = false;
}
watch(() => [props.file], () => {
  readerFile(props.file)
}, { immediate: true})
</script>

<template>
  <div class="text-container">
    <iframe v-if="isIfarme" scrolling="no"  border="0" frameborder="no" framespacing="0" allowfullscreen="true" :src="props.file"></iframe>
    <pre v-if="isTxt" id="text-container">{{ txtContainer }}</pre>
    <a-spin v-if="isLoading" dot />
  </div>
</template>


<style lang="scss">
.text-container {
  height: 100%;
  width: 100%;
  margin: 0 auto;

  iframe {
    height: 100%;
    width: 100%;
  }
  pre {
    box-sizing:border-box;
    /*以下样式是自动换行代码*/
    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
    /*以上样式是自动换行代码，需要的加上，不需要的删除*/
    overflow:auto;
    font-family:Menlo, Monaco, Consolas, 'Courier New', monospace;
    font-size:13px;
    padding:9.5px;
    margin-top:0px;
    margin-bottom:10px;
    line-height:1.42857;
    color:#333333;
    word-break:break-all;
    word-wrap:break-word;
    border:1px solid #CCCCCC;
    border-radius:4px;
    background-color:#F5F5F5;}
}
</style>
